package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.adapter.AvatarAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.StringUtil;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 展示直播间的头像
 * 第一个以大图展示，并且显示昵称
 * 当在直播的时候显示主播的头像
 * 其他时间显示管理员的头像
 */
public class AvatarListView extends RelativeLayout {
    private static final String TAG = "AvatarListView";
    private RecyclerView rv_audienceAvatar;
    private TextView tv_audienceNum;
    private AvatarAdapter avatarAdapter;
    private List<User> audienceList = new ArrayList<>();
    private Context context;
    private LiveRoom liveRoom;
    private boolean haveFirstLoadUserInfo;
    private ImageView iv_anchorAvatar;
    private TextView tv_anchorName;
    private View ll_anchorContainer;
    private User manager;
    private User anchor;
    private User loginUserInfo;
    private int audienceSize;
    private int page = 1;

    public AvatarListView(@NonNull Context context) {
        super(context);
        this.context = context;
        init();
    }

    public AvatarListView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public AvatarListView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    //提出部分init内容到构造函数去执行，是避免空指针异常，（当两个用户同时进入某个非直播状态的直播间，其中一个用户会出现avatarAdapter的空指针异常而导致程序崩溃）
    private void init() {
        inflate(context, R.layout.live_room_toolbar, this);
        avatarAdapter = new AvatarAdapter(context, audienceList);
        ll_anchorContainer = findViewById(R.id.ll_anchor_container);
        tv_anchorName = findViewById(R.id.tv_anchor_nick);
        iv_anchorAvatar = findViewById(R.id.img_icon);
        rv_audienceAvatar = findViewById(R.id.rv_audience_avatar);
        tv_audienceNum = findViewById(R.id.audience_num);
        rv_audienceAvatar.setAdapter(avatarAdapter);
        rv_audienceAvatar.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        ll_anchorContainer.setOnClickListener(v -> {
            if (anchor != null) {
                showUserDetailDialog(anchor);
            } else if (manager != null) {
                showUserDetailDialog(manager);
            }
        });
        loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
    }

    public void init(LiveRoom liveRoom) {
        this.liveRoom = liveRoom;
        //audienceSize = liveRoom.getAudienceSize();
        //refreshAudienceNumber();
        //管理员进入直播的情况
        if (manager == null && TextUtils.equals(liveRoom.getManagerId(), loginUserInfo.getuId())) {
            manager = loginUserInfo;
            if (anchor == null) {//如果主播信息是空的，显示管理员头像
                showManager();
            }
        }
        loadAudienceUserInfoFromService();
    }

    private void showUserDetailDialog(User user) {
        UserDetailsDialog detailsDialog_1 = new UserDetailsDialog(context, user);
        detailsDialog_1.setUserDetailsDialogListener(new UserDetailsDialog.UserDetailsDialogListener() {
            @Override
            public void onMentionClick(String username) {

            }

            @Override
            public void onMessageClick(User user) {
                context.startActivity(new Intent(context, ChatActivity.class).putExtra(Constant.EXTRA_TARGET_USER_INFO, user));
            }
        });
        detailsDialog_1.show();
    }

    public void onUserJoin(User user) {
        if (manager != null && TextUtils.equals(manager.getuId(), user.getuId())) {
            return;//到此直接返回，因为管理员默认存在于房间中，不参与观众数量的统计
        }
        //重复判断,只与观众列表前面面20个做判断
        int maxCheck = audienceList.size() <= 20 ? audienceList.size() : 20;
        for (int i = 0; i < maxCheck; i++) {
            if (TextUtils.equals(audienceList.get(i).getuId(), user.getuId())) {
                return;
            }
        }
        audienceList.add(user);
        if (audienceList.size() < 20) {//小等于20个的时候，才去刷新头像列表
            avatarAdapter.notifyItemInserted(audienceList.size() - 1);
        }
        audienceSize++;
        refreshAudienceNumber();
    }


    public void onUserExited(String userId) {

        if (liveRoom == null || TextUtils.equals(userId, liveRoom.getManagerId())) {
            return;
        }
        for (int i = 0; i < audienceList.size(); i++) {
            if (TextUtils.equals(audienceList.get(i).getuId(), userId)) {
                audienceList.remove(i);
                avatarAdapter.notifyItemRemoved(i);
                avatarAdapter.notifyItemRangeChanged(i, audienceList.size() - i);
                break;
            }
        }
        // notifyLiveRoomMemberChange();
        audienceSize--;
        refreshAudienceNumber();
    }


    protected void refreshAudienceNumber() {
        tv_audienceNum.setText(Utils.numberFormat(audienceSize));
    }


    protected void refreshAudienceList(List<User> userList) {
        refreshAudienceNumber();
        if (page == 1) {
            audienceList.clear();   //避免多个用户同时进入直播间时，直播间用户列表的数据还没又请求回来的时候就已经执行onUserJoin()方法导致的用户user重复加载进audienceList集合，导致直播间重复显示用户头像的问题
        }
        audienceList.addAll(userList);
        avatarAdapter.notifyDataSetChanged();

    }

    protected void refreshAudienceList(User user) {

        audienceList.add(user);
        avatarAdapter.notifyItemInserted(audienceList.size() - 1);


    }

    public void notifyDataSetChanged() {
        avatarAdapter.notifyDataSetChanged();
    }

    public void notifyItemChanged(int index) {
        avatarAdapter.notifyItemChanged(index);
    }

    public void showAnchorAvatar(User anchor) {
        if (anchor == null) {
            return;
        }
        this.anchor = anchor;
        //如果主播就是管理员，无须切换头像
        if (TextUtils.equals(anchor.getuId(), liveRoom.getManagerId())) {
            return;
        }
        for (int i = 0; i < audienceList.size(); i++) {
            if (TextUtils.equals(audienceList.get(i).getuId(), anchor.getuId())) {
                audienceList.remove(i);
                avatarAdapter.notifyItemRemoved(i);
                avatarAdapter.notifyItemRangeChanged(i, audienceList.size() - i);
                break;
            }
        }

        if (!ll_anchorContainer.isShown()) {
            ll_anchorContainer.setVisibility(VISIBLE);
        }
        if (!iv_anchorAvatar.isShown()) {
            iv_anchorAvatar.setVisibility(VISIBLE);
        }
//        Glide.with(context)
//                .load(anchor.getAvatar())
//                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .into(iv_anchorAvatar);
        GlideLoadUtils.glideLoad(context, anchor.getAvatar(), iv_anchorAvatar);
        tv_anchorName.setText(anchor.getUsername());
    }

    public void showManager(User manager) {
        this.manager = manager;
        for (int i = 0; i < audienceList.size(); i++) {
            if (TextUtils.equals(audienceList.get(i).getuId(), manager.getuId())) {
                audienceList.remove(i);
                break;
            }
        }
        showManager();
    }

    private void showManager() {

        if (!ll_anchorContainer.isShown()) {
            ll_anchorContainer.setVisibility(VISIBLE);
        }
        if (!iv_anchorAvatar.isShown()) {
            iv_anchorAvatar.setVisibility(VISIBLE);
        }
//        Glide.with(context)
//                .load(manager.getAvatar())
//                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .into(iv_anchorAvatar);
//
        GlideLoadUtils.glideLoad(context, manager.getAvatar(), iv_anchorAvatar);
        tv_anchorName.setText(manager.getUsername());
    }


    /**
     * 直播结束，重新显示管理员头像，并把主播添加进观众列表的第一个
     */
    public void hideAnchorAvatar() {

        if (anchor == null) {
            return;
        }
        //如果主播就是管理员，无须切换头像
        if (TextUtils.equals(anchor.getuId(), liveRoom.getManagerId())) {
            return;
        }
        if (manager != null) {
            showManager();
        } else {
            ll_anchorContainer.setVisibility(GONE);
        }
        audienceList.add(0, anchor);
        avatarAdapter.notifyItemInserted(0);
        anchor = null;
    }


    public Integer getAudienceSize() {
        return audienceSize;
    }


    private void loadAudienceUserInfoFromService() {
        haveFirstLoadUserInfo = true;
        Map<String, Object> body = new HashMap<>();
        body.put("liveRoomId", liveRoom.getId());
        body.put("page", page);
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .getChannelUsersInfo_v1(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        if (result.getData() == null) {
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        List<User> userList = jsonObject.getJSONArray("userList").toJavaList(User.class);
                        if (page == 1) {
                            audienceSize = jsonObject.getInteger("audienceSize");
                            //遍历获取管理员信息，或许管理员信息应该直接缓存在 liveRoom 里面
                            for (int i = 0; i < userList.size(); i++) {
                                String uId = userList.get(i).getUId();
                                if (StringUtil.equals(liveRoom.getManagerId(), uId)) {
                                    manager = userList.get(i);
                                    // audienceSize++;//把管理员也算一个，加进去，不管管理员是否真实的在里面
                                    userList.remove(i);
                                    break;
                                }
                            }
                        }
                        //清除主播用户信息
                        if (anchor != null) {
                            for (int i = 0; i < audienceList.size(); i++) {
                                if (TextUtils.equals(audienceList.get(i).getuId(), anchor.getuId())) {
                                    userList.remove(i);
                                    break;
                                }
                            }
                        }
                        //如果主播头像不为空，说明此刻在显示主播头像，就不显示管理员头像
                        if (anchor == null && manager != null) {
                            showManager();
                        } else if (anchor == null) { //主播为空，表示非直播情况下，管理员移除，则 隐藏掉 ll_anchorContainer
                            ll_anchorContainer.setVisibility(GONE);
                        }

                        if (!TextUtils.equals(liveRoom.getManagerId(), loginUserInfo.getuId())) {//不是管理员，才加进头像列表尾部
                            userList.add(loginUserInfo);//把自己添加进观众列表
                        }
                        refreshAudienceList(userList);
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    /**
     * 移交管理成功后,刷新头像
     */
    public void refreshHead(LiveRoom refreshLiveRoom, User managerUser) {
        this.manager = managerUser;
        if (anchor == null) {//判断是否在直播中，
            showManager();
        }


    }

    public void onManagerRemove() {
        //主播为空，表示非直播情况下，管理员移除，则 隐藏掉 ll_anchorContainer
        if (anchor == null) {
            ll_anchorContainer.setVisibility(GONE);
        }
//        iv_anchorAvatar.setVisibility(GONE);
//        tv_anchorName.setText("管理空缺中");
    }

    /**
     * 游客登录后，调用
     *
     * @param myUserInfo
     */
    public void loginUserJoin(User myUserInfo) {
        loginUserInfo = myUserInfo;
        //管理员进入直播的情况
        if (TextUtils.equals(liveRoom.getManagerId(), loginUserInfo.getuId())) {
            manager = loginUserInfo;
            if (anchor == null) {//如果主播信息是空的，显示管理员头像
                showManager();
            }
        } else {
            audienceSize++;
            refreshAudienceNumber();
            refreshAudienceList(loginUserInfo);
        }
    }
}
